package com.tianze.library.view;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.widget.EditText;

import com.tianze.library.R;


public class WithDeleteEditText extends EditText {
    boolean isAdd = false;
    float x = 0;
    float y = 0;
    float imgX = 0;

    public WithDeleteEditText(Context context, AttributeSet attrs) {
        super(context, attrs);
        setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                if (x > imgX) {
                    setText("");
                }
            }
        });
        if (!"".equals(getText().toString())) {
            isAdd = true;
        }
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        if (isAdd && hasFocus()) {
            Bitmap bitmap = BitmapFactory
                    .decodeResource(getResources(), R.drawable.ic_delete);
            Paint paint = new Paint();
            paint.setTextSize(30);
            paint.setTextScaleX(1);
            paint.setColor(Color.BLACK);
            float h = this.getHeight();
            float h2 = bitmap.getHeight();
            float f = h / 2 - (h2 / 2);
            imgX = (float) (getWidth() - (bitmap.getWidth() * 1.1) - 10);
            canvas.drawBitmap(bitmap, imgX, f, paint);
        }
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        x = event.getX();
        y = event.getY();
        return super.onTouchEvent(event);
    }

    @Override
    protected void onTextChanged(CharSequence text, int start, int lengthBefore, int lengthAfter) {
        super.onTextChanged(text, start, lengthBefore, lengthAfter);
        String temp = getText().toString();
        if ("".equals(temp)) {
            isAdd = false;
        } else {
            isAdd = true;
        }

    }

}
